
#include "xdns-unix-like-init.h"
#include <string.h>
#include <fstream>

using namespace std;

const unsigned short DEFAULT_PORT = 53;
const char RESOLV_CONF_PATH[] = "/etc/resolv.conf";
const char NAME_SERVER_KEY[] = "nameserver";

XdnsUnixLikeInit::XdnsUnixLikeInit()
: XdnsInit()
{
}

XdnsUnixLikeInit::~XdnsUnixLikeInit()
{
}

void
XdnsUnixLikeInit::GetSystemResolvers(vector<XdnsServerConfig>& servers)
{
    size_t keySize = strlen(NAME_SERVER_KEY);
    ifstream fs(RESOLV_CONF_PATH);
    while (fs.good())
    {
        string line;
        getline(fs, line);
        if (!(fs.good()))
        {
            break;
        }

        if (line.compare(0, keySize, NAME_SERVER_KEY) != 0)
        {
            continue;
        }

        size_t found = line.find_first_not_of(" \t", keySize);
        if ((string::npos == found) || (keySize == found))
        {
            continue;
        }

        XdnsServerConfig systemServer(DEFAULT_PORT,
                                      line.substr(found));
        servers.push_back(systemServer);
    }
}

